package com.reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionTest {
//    使用反射之前可以执行的操作
    @Test
    public void test1(){
        //1、创建person的实例对象
        Person person = new Person();
        System.out.println(person);

        //2、调用属性
        person.age = 10;
        System.out.println(person.age);

        //3、调用方法
        person.show();

    }

    @Test
    public void test2() throws Exception {
        //1、创建Person类的实例
        Class<Person> clazz = Person.class;
        Person p1 = clazz.newInstance();
        System.out.println(p1);

        //2、调用属性
        Field ageField = clazz.getField("age");
        ageField.set(p1,10);
        System.out.println(ageField.get(p1));

        //3、调用方法
        Method showMethod = clazz.getMethod("show");
        showMethod.invoke(p1);

    }
//    暴力反射
    @Test
    public void test3() throws Exception {
        //1、创建Person类的实例
        Class<Person> clazz = Person.class;
        Constructor<Person> cons =
                clazz.getDeclaredConstructor(String.class, int.class);
        cons.setAccessible(true);
        Person p1 = cons.newInstance("张三", 12);

        //2、调用私有属性
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(p1,"李四");
        System.out.println(nameField.get(p1));

        //3、调用私有的方法
        Method shownNationMethod = clazz.getDeclaredMethod("showNation", String.class);
        shownNationMethod.setAccessible(true);
        String info = (String) shownNationMethod.invoke(p1,"中国");
        System.out.println(info);
    }




}
